﻿#include "tcp.h"
#include "ui_tcp.h"
#include "server_file.h"
#include "client_file.h"
Tcp::Tcp(QTcpSocket *tcpSocket, QString myID, QWidget *parent)
    : QWidget{parent}
    , ui(new Ui::Tcp)
{
    {
        this->tcpSocket = tcpSocket;
        this->myID = myID;
        ui->setupUi(this);
        setWindowTitle("Server");
        QHostAddress peerAddress = this->tcpSocket->peerAddress();
        client_IP = peerAddress.toString();
        this->setWindowTitle(client_IP);
        ui->recvEdit->append("连接用户(IP:" + client_IP + ") 成功！");
        connect(tcpSocket, &QTcpSocket::readyRead, this, &Tcp::readyRead_Slot);
        connect(ui->sendButton, &QPushButton::clicked, this, &Tcp::on_sendButton_clicked);
        connect(tcpSocket, &QTcpSocket::disconnected, this, &Tcp::on_disconnected);
    }
}


void Tcp::readyRead_Slot()    //读取数据槽函数
{
    QByteArray msg_array =QByteArray(1000,0);
    msg_array = tcpSocket->readAll();
    QDataStream stream(&msg_array,QIODevice::ReadOnly);
    ui->recvEdit->setTextColor(QColor(Qt::blue));
    QString name, msg;
    stream >> name >> msg;
    ui->recvEdit->append(name + ":" + msg);

}


Tcp::~Tcp()
{
    // 确保在析构时断开连接
    if (tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        qDebug() << "Disconnecting from host...";
        tcpSocket->disconnectFromHost();
        if (tcpSocket->state() != QAbstractSocket::UnconnectedState)
        {
            // 等待断开
            tcpSocket->waitForDisconnected(3000); // 3秒超时
        }
    }
    delete tcpSocket;
    delete ui;
}

//处理断开连接
void Tcp::on_disconnected()
{
    ui->recvEdit->append("对方已断开连接！");
    delete tcpSocket;
}



void Tcp::on_sendButton_clicked()    //发送按钮按下
{
    ui->recvEdit->setTextColor(QColor(210,105,30));
    QByteArray buf;
    QDataStream stream(&buf, QIODevice::WriteOnly);
    QString text = ui->sendEdit->toPlainText();
    if(!text.isEmpty())
    {
        stream<< this->myID << text;
        if(tcpSocket)
        {
            tcpSocket->write(buf);
        }
        else
        {
            QMessageBox::warning(this, "警告", "发送失败！已断开连接");
        }
        qDebug() << "Sending message:" << ui->sendEdit->toPlainText();
        ui->recvEdit->append("我：" + ui->sendEdit->toPlainText());
        ui->sendEdit->clear();
    }
}

void Tcp::on_SendFileButton_clicked()
{
    server_file * a= new server_file;
    a->show();
}


void Tcp::on_recvButton_clicked()
{
    client_file *a = new client_file(0,this->client_IP);
    a->show();
}

